package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.constants.MQConstants;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.*;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class GoodsService {
    private final SpuMapper spuMapper;
    private final SpuDetailMapper detailMapper;
    private final BrandService brandService;
    private final CategoryService categoryService;
    private final SkuMapper skuMapper;
    private final AmqpTemplate amqpTemplate;

    public GoodsService(SpuMapper spuMapper, SpuDetailMapper detailMapper, BrandService brandService, CategoryService categoryService, SkuMapper skuMapper, AmqpTemplate amqpTemplate) {
        this.spuMapper = spuMapper;
        this.detailMapper = detailMapper;
        this.brandService = brandService;
        this.categoryService = categoryService;
        this.skuMapper = skuMapper;
        this.amqpTemplate = amqpTemplate;
    }

    public PageDTO<SpuDTO> querySpuByPage(
            Integer page, Integer rows, Boolean saleable, Long categoryId, Long brandId, Long id) {
        // spu的非空字段作为查询条件，and关系
        Spu spu = new Spu();
        spu.setId(id);
        spu.setSaleable(saleable);
        spu.setBrandId(brandId);
        spu.setCid3(categoryId);
        // 分页
        Page<Spu> result = PageHelper.startPage(page, rows);
        // 查询结果
        List<Spu> list = spuMapper.select(spu);
        // 转换DTO
        List<SpuDTO> dtoList = BeanHelper.copyWithCollection(list, SpuDTO.class);

        // 查询每个spu的分类和品牌的名称
        handleCategoryAndBrandName(dtoList);

        return new PageDTO<>(result.getTotal(), result.getPages(), dtoList);
    }

    private void handleCategoryAndBrandName(List<SpuDTO> dtoList) {
        for (SpuDTO spuDTO : dtoList) {
            handleCategoryAndBrandName(spuDTO);
        }
    }

    private void handleCategoryAndBrandName(SpuDTO spuDTO) {
        // 1.处理分类名称
        // 1.1获取商品有关的分类的id
        List<Long> categoryIds = spuDTO.getCategoryIds();
        // 1.2.根据分类的id查询分类集合
        //List<CategoryDTO> list = categoryService.queryByIds(categoryIds);
        // 1.3.把分类集合的名称，拼接起来
            /*StringBuilder sb = new StringBuilder();
            for (CategoryDTO categoryDTO : list) {
                sb.append(categoryDTO.getName()).append("/");
            }
            sb.deleteCharAt(sb.length() - 1);*/
        String name = categoryService.queryByIds(categoryIds)
                .stream()
                .map(CategoryDTO::getName)
                .collect(Collectors.joining("/"));

        // 1.4.设置分类名称
        spuDTO.setCategoryName(name);
        // 2.处理品牌名称
        // 2.1.获取品牌的id
        Long brandId = spuDTO.getBrandId();
        // 2.2.根据品牌id查询品牌
        BrandDTO brand = brandService.findById(brandId);
        if (brand != null) {
            // 查询成功，设置品牌名称
            spuDTO.setBrandName(brand.getName());
        }
    }

    @Transactional
    public void saveGoods(SpuDTO spuDTO) {
        // 1.新增spu
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        // 默认商品是下架的
        spu.setSaleable(false);
        spuMapper.insertSelective(spu);

        // 2.新增spuDetail
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        SpuDetail detail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
        detail.setSpuId(spu.getId());
        detailMapper.insertSelective(detail);

        // 3.新增sku
        saveSkuFromSpuDTO(spuDTO, spu.getId());

    }

    private void saveSkuFromSpuDTO(SpuDTO spuDTO, Long spuId) {
        // 3.新增Sku
        List<SkuDTO> skuDTOList = spuDTO.getSkus();
        if(CollectionUtils.isEmpty(skuDTOList)){
            throw new LyException(400, "商品SKU不能为空");
        }
        List<Sku> skuList = new ArrayList<>();
        for (SkuDTO skuDTO : skuDTOList) {
            Sku sku = BeanHelper.copyProperties(skuDTO, Sku.class);
            sku.setSpuId(spuId);
            // 默认是下架
            sku.setEnable(false);
            skuList.add(sku);
        }
        // 批量新增
        skuMapper.insertList(skuList);
    }

    @Transactional
    // update tb_spu set saleable = true where id = 1
    public void updateSaleable(Long id, Boolean saleable) {
        // 1.根据主键修改SPU的saleable字段
        Spu spu = new Spu();
        spu.setId(id);
        spu.setSaleable(saleable);
        spuMapper.updateByPrimaryKeySelective(spu);
        // 2.更新sku表中的enable字段为saleable .// update tb_sku set enable = true where spu_id = 1
        // 2.1.要修改的数据 Sku的非空字段，就是要修改的数据
        Sku sku = new Sku();
        sku.setEnable(saleable);
        // 2.2.修改的where条件 Example
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId", id);
        skuMapper.updateByExampleSelective(sku, example);

        // 发送消息
        String routingKey = saleable ? MQConstants.RoutingKey.ITEM_UP_KEY:MQConstants.RoutingKey.ITEM_DOWN_KEY;
        amqpTemplate.convertAndSend(MQConstants.Exchange.ITEM_EXCHANGE_NAME, routingKey, id);
    }

    public SpuDTO querySpuById(Long id) {
        // 1.查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        // 2.转换DTO
        SpuDTO spuDTO = BeanHelper.copyProperties(spu, SpuDTO.class);
        // 3.填充spuDetail
        spuDTO.setSpuDetail(queryDetailById(id));
        // 4.添加skus
        spuDTO.setSkus(querySkuListBySpuId(id));
        // 5.添加category和brand的name
        handleCategoryAndBrandName(spuDTO);
        return spuDTO;
    }

    public List<SkuDTO> querySkuListBySpuId(Long spuId) {
        Sku record = new Sku();
        record.setSpuId(spuId);
        List<Sku> list = skuMapper.select(record);
        return BeanHelper.copyWithCollection(list, SkuDTO.class);
    }

    public SpuDetailDTO queryDetailById(Long spuId) {
        SpuDetail detail = detailMapper.selectByPrimaryKey(spuId);
        return BeanHelper.copyProperties(detail, SpuDetailDTO.class);
    }

    @Transactional
    public void updateGoods(SpuDTO spuDTO) {
        Long id = spuDTO.getId();
        if (id == null) {
            throw new LyException(400, "商品ID不能为空！");
        }
        // 1.修改SPU
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        spu.setSaleable(false);
        spuMapper.updateByPrimaryKeySelective(spu);

        // 2.修改SpuDetail
        SpuDetailDTO detailDTO = spuDTO.getSpuDetail();
        SpuDetail detail = BeanHelper.copyProperties(detailDTO, SpuDetail.class);
        detail.setSpuId(id);
        detailMapper.updateByPrimaryKeySelective(detail);

        // 3.删除sku delete from tb_sku where spu_id = 1
        Sku record = new Sku();
        record.setSpuId(id);
        skuMapper.delete(record);

        // 4.新增sku
        saveSkuFromSpuDTO(spuDTO, id);
    }

    public List<SkuDTO> querySkuByIds(List<Long> ids) {
        List<Sku> list = skuMapper.selectByIdList(ids);
        return BeanHelper.copyWithCollection(list, SkuDTO.class);
    }

    @Transactional
    public void minusStock(Map<Long, Integer> skuMap) {
        try {
            for (Map.Entry<Long, Integer> entry : skuMap.entrySet()) {
                Long skuId = entry.getKey();
                Integer num = entry.getValue();
                // 减库存
                skuMapper.minusStock(skuId, num);
            }
        } catch (Exception e) {
            throw new LyException(500, "库存不足！");
        }
    }

    @Transactional
    public void plusStock(Map<Long, Integer> skuMap) {
        try {
            for (Map.Entry<Long, Integer> entry : skuMap.entrySet()) {
                Long skuId = entry.getKey();
                Integer num = entry.getValue();
                // 加库存
                skuMapper.minusStock(skuId, -num);
            }
        } catch (Exception e) {
            throw new LyException(500, "恢复库存失败！");
        }
    }
}
